package resourseMonitor

import (
	"log"
	"runtime"
	"syscall"
	"time"
)

func MonitorResourse() {
	for {
		diskInfo := DiskUsage("/tmp") // TODO: use cache path
		log.Println("Disk used:", diskInfo.Used, "/", diskInfo.All)
		memInfo := MemStat()
		log.Println("Memory used:", memInfo.Used, "/", memInfo.All)
		time.Sleep(3 * time.Minute) // check every 3 minutes
	}
}

type DiskStatus struct {
	All  uint64 `json:"all"`
	Used uint64 `json:"used"`
	Free uint64 `json:"free"`
}

// disk usage of path/disk
func DiskUsage(path string) (disk DiskStatus) {
	fs := syscall.Statfs_t{}
	err := syscall.Statfs(path, &fs)
	if err != nil {
		return
	}
	disk.All = fs.Blocks * uint64(fs.Bsize)
	disk.Free = fs.Bfree * uint64(fs.Bsize)
	disk.Used = disk.All - disk.Free
	return
}

type MemStatus struct {
	All  uint32 `json:"all"`
	Used uint32 `json:"used"`
	Free uint32 `json:"free"`
	Self uint64 `json:"self"`
}

func MemStat() MemStatus {
	memStat := new(runtime.MemStats)
	runtime.ReadMemStats(memStat)
	mem := MemStatus{}
	mem.Self = memStat.Alloc

	//system memory usage
	sysInfo := new(syscall.Sysinfo_t)
	err := syscall.Sysinfo(sysInfo)
	if err == nil {
		mem.All = uint32(int(sysInfo.Totalram) * syscall.Getpagesize())
		mem.Free = uint32(int(sysInfo.Freeram) * syscall.Getpagesize())
		mem.Used = mem.All - mem.Free
	}
	return mem
}
